package com.dq.rbac.commons.security;

import com.dq.rbac.commons.exception.UserCountLockException;
import com.dq.rbac.entity.SysUser;
import com.dq.rbac.service.SysUserService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @project: rbac
 * @ClassName: 自定义查库实现操作
 * @author: dq
 * @creat: 2022/12/26 15:08
 */
@Service
public class MyUserDetailServiceImpl implements UserDetailsService {

    @Resource
    private SysUserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //service查询用户
        SysUser user = userService.getByUserName(username);
        if (user == null) {
            //如果没有查询成功 我们直接抛出认证异常
            throw new UsernameNotFoundException("用户名或密码错误");
        } else if ("1".equals(user.getStatus())) {
            throw new UserCountLockException("该用户账户已被上锁，请联系管理人员");
        }
        //此User是UserDetails提供的
        return new User(user.getUsername(), user.getPassword(), getUserAuthority(user.getId()));
    }

    public List<GrantedAuthority> getUserAuthority(Long userId) {
        //返回一些User的权限
        //格式  ROLE_admin,ROLE_common,system:user:resetPwd,system:role:delete,system:user:list,system:menu:query,system:menu:list,system:menu:add,system:user:delete,system:role:list,system:role:menu,system:user:edit,system:user:query,system:role:edit,system:user:add,system:user:role,system:menu:delete,system:role:add,system:role:query,system:menu:edit
        String userAuthorityInfo = userService.getUserAuthorityInfo(userId);
        return AuthorityUtils.commaSeparatedStringToAuthorityList(userAuthorityInfo);
    }
}
